package main

import (
	"context"
	"fmt"
	"go-vue3-ts-nativeUI-unocss/internal/auth"
	"go-vue3-ts-nativeUI-unocss/internal/config"
	"go-vue3-ts-nativeUI-unocss/internal/models"
	"go-vue3-ts-nativeUI-unocss/internal/services"
	"time"
)

// App struct
type App struct {
	ctx         context.Context
	authService *auth.AuthService
	configMgr   *config.ConfigManager
	logService  *services.LogService
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{
		authService: auth.NewAuthService(),
		configMgr:   config.GetConfigManager(),
		logService:  services.GetLogService(),
	}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

// Login 登录验证（暴露给前端）
func (a *App) Login(loginID, loginKey string) (map[string]interface{}, error) {
	// 调用认证服务
	result, err := a.authService.Login(loginID, loginKey)
	if err != nil {
		return map[string]interface{}{
			"code":   500,
			"result": false,
			"msg":    fmt.Sprintf("登录异常: %v", err),
		}, nil
	}

	// 如果登录成功，保存配置
	if result.Code == 0 && result.Result {
		loginConfig := &config.LoginConfig{
			LoginID:             loginID,
			LoginKey:            loginKey,
			RememberCredentials: true,
		}
		if err := a.configMgr.SetLoginConfig(loginConfig); err != nil {
			// 记录错误但不影响登录结果
			a.logService.Error("app", "保存登录配置失败", map[string]interface{}{
				"error": err.Error(),
			})
		}
	}

	// 返回结果
	return map[string]interface{}{
		"code":   result.Code,
		"result": result.Result,
		"msg":    result.Message,
	}, nil
}

// GetLoginConfig 获取保存的登录配置（暴露给前端）
func (a *App) GetLoginConfig() (map[string]interface{}, error) {
	config := a.configMgr.GetLoginConfig()
	return map[string]interface{}{
		"loginId":             config.LoginID,
		"loginKey":            config.LoginKey,
		"rememberCredentials": config.RememberCredentials,
	}, nil
}

// SaveAppConfig 保存应用配置（暴露给前端）
func (a *App) SaveAppConfig(key string, value map[string]interface{}) error {
	if key == "login" {
		loginConfig := &config.LoginConfig{
			LoginID:             getString(value, "loginId"),
			LoginKey:            getString(value, "loginKey"),
			RememberCredentials: getBool(value, "rememberCredentials"),
		}
		return a.configMgr.SetLoginConfig(loginConfig)
	}
	// 可以添加其他配置项的保存逻辑
	return nil
}

// GetAppConfig 获取应用配置（暴露给前端）
func (a *App) GetAppConfig(key string) (map[string]interface{}, error) {
	if key == "login" {
		return a.GetLoginConfig()
	}
	// 可以添加其他配置项的获取逻辑
	return nil, nil
}

// 辅助函数
func getString(m map[string]interface{}, key string) string {
	if v, ok := m[key].(string); ok {
		return v
	}
	return ""
}

func getBool(m map[string]interface{}, key string) bool {
	if v, ok := m[key].(bool); ok {
		return v
	}
	return false
}

// WriteLog 写入日志（暴露给前端）
func (a *App) WriteLog(level, module, message string, data map[string]interface{}) error {
	logLevel := models.LogLevel(level)
	a.logService.Log(logLevel, module, message, data)
	return nil
}

// GetLogs 获取日志（暴露给前端）
func (a *App) GetLogs(query map[string]interface{}) (map[string]interface{}, error) {
	logQuery := models.LogQuery{}

	// 解析查询参数
	if level, ok := query["level"].(string); ok {
		logQuery.Level = level
	}
	if module, ok := query["module"].(string); ok {
		logQuery.Module = module
	}
	if limit, ok := query["limit"].(float64); ok {
		logQuery.Limit = int(limit)
	}

	// 解析时间
	if startTimeStr, ok := query["startTime"].(string); ok {
		if t, err := time.Parse(time.RFC3339, startTimeStr); err == nil {
			logQuery.StartTime = &t
		}
	}
	if endTimeStr, ok := query["endTime"].(string); ok {
		if t, err := time.Parse(time.RFC3339, endTimeStr); err == nil {
			logQuery.EndTime = &t
		}
	}

	response := a.logService.GetLogs(logQuery)

	// 转换为前端需要的格式
	logs := make([]map[string]interface{}, len(response.Logs))
	for i, log := range response.Logs {
		logs[i] = map[string]interface{}{
			"time":    log.Time.Format(time.RFC3339),
			"level":   string(log.Level),
			"module":  log.Module,
			"message": log.Message,
			"data":    log.Data,
		}
	}

	return map[string]interface{}{
		"logs":  logs,
		"total": response.Total,
	}, nil
}

// ClearLogs 清空日志（暴露给前端）
func (a *App) ClearLogs() error {
	a.logService.ClearLogs()
	return nil
}
